import { EditGoods } from "@/components/form/companies/edit.goods"
import { FormModal } from "@/components/modal/form.modal"
import { Field_Search } from "@/components/utils/field.list"
import goodsService from "@/services/goods.service"
import { StoreContext } from "@/store"
import { AsyncModal, IndexRender, FormRender, ListTable, DateRender, OperateRender } from "@whzhuke/antd"
import { functionCommon } from "@whzhuke/common"
import { useMobx } from "@whzhuke/mobx"
import { Button, Col, Form, InputNumber, Row, Space } from "antd"
import { useForm } from "antd/es/form/Form"
import React, { useCallback, useContext } from "react"

// 单位映射：数字 -> 文字（用于表格显示）
const unitDisplayMap: Record<number, string> = {
  1: "套",
  2: "件",
  3: "个",
  4: "台"
}

// 货币单位映射：RMB=人民币, USD=美元（用于表格显示）
const currencyDisplayMap: Record<string | number, string> = {
  RMB: "¥",
  USD: "$",
  人民币: "¥",
  美元: "$",
  1: "¥", // 兼容数字格式
  2: "$" // 兼容数字格式
}

const Page = useMobx(() => {
  const [form] = useForm()
  const { ListStore } = useContext(StoreContext)

  const unitRender = useCallback((val: any) => {
    return unitDisplayMap[val] || val || "-"
  }, [])

  const priceRender = useCallback((val: any, item: any) => {
    const price = Number(val)
    if (isNaN(price)) return "-"
    const currency = item?.currency
    const currencySymbol = currencyDisplayMap[currency] || currencyDisplayMap[String(currency)] || currencyDisplayMap[Number(currency)] || "¥"
    return `${currencySymbol} ${price.toFixed(2)}`
  }, [])

  const imgRender = useCallback((val: string) => {
    if (!val) {
      return "-"
    }
    return <img src={`${functionCommon.requestHost("public")}${val}`} alt="产品文件" style={{ width: 72, height: 72, objectFit: "cover" }} />
  }, [])

  const titleRender = useCallback(() => {
    return (
      <Row justify="space-between" align="middle">
        <Col> </Col>
        <Col>
          <Space size="middle">
            <Button type="primary" onClick={AddModal()}>
              添加
            </Button>
            <Button type="primary" onClick={Zanwu()}>
              导出
            </Button>
          </Space>
        </Col>
      </Row>
    )
  }, [])
  const Zanwu = useCallback(() => async () => {}, [])
  const AddModal = useCallback(
    (value?: any) => async () => {
      const done = await AsyncModal({
        content: FormModal,
        params: {
          formProps: {
            value
          },
          formEle: EditGoods,
          title: "添加产品"
        }
      })
      if (done) {
        ListStore.updateList(goodsService.list)
      }
    },
    []
  )
  const onFinish = useCallback(data => {
    const [start, end] = data.range || []
    data.startTime = start ? new Date(start).getTime() : undefined
    data.endTime = end ? new Date(end).getTime() : undefined
    delete data.range
    ListStore.setParams(goodsService.list, data)
  }, [])
  const EditModal = useCallback(
    (val?, item?) => async () => {
      const done = await AsyncModal({
        content: FormModal,
        params: {
          formEle: EditGoods,
          formProps: {
            values: item
          },
          title: item ? "修改产品" : "添加产品"
        }
      })
      if (done) {
        ListStore.updateList(goodsService.list)
      }
    },
    []
  )

  return (
    <Row>
      <Col span={24}>
        <FormRender
          form={form}
          onFinish={onFinish}
          layout="inline"
          fieldList={[
            {
              fieldType: "rangeDate",
              formItemConfig: {
                name: "range",
                label: "创建时间"
              },
              config: {
                showTime: !0,
                format: "YYYY-MM-DD HH:mm:ss"
              }
            },
            {
              fieldType: "input",
              formItemConfig: {
                label: "产品名称",
                name: "keyword"
              },
              config: {
                placeholder: "产品名称"
              }
            },
            {
              fieldType: "diy",
              formItemConfig: {
                label: "产品价格"
              },
              component: (
                <Space>
                  <Form.Item name="minPrice" noStyle>
                    <InputNumber placeholder="最低价格" min={0} precision={2} />
                  </Form.Item>
                  <span>- -</span>
                  <Form.Item name="maxPrice" noStyle>
                    <InputNumber placeholder="最高价格" min={0} precision={2} />
                  </Form.Item>
                </Space>
              )
            },

            Field_Search
          ]}
        />
      </Col>
      <Col span={24}>
        <ListTable
          title={titleRender}
          apiColumns={[
            IndexRender("id", 80),
            ["imgPath", "产品文件", imgRender],
            ["name", "产品名称"],
            ["unit", "单位", unitRender],
            ["marketPrice", "产品价格", priceRender],
            ["stockNums", "库存量"],
            ["description", "产品描述"],
            ["paramDes", "产品要求"],
            ["createTs", "创建时间", DateRender()],
            ["id", "操作", OperateRender([["修改", EditModal]]), { width: 80, fixed: "right" }]
          ]}
          apiService={goodsService.list}
          // testData={goodsTestData}
        />
      </Col>
    </Row>
  )
})

export default Page
